//
//  XMChatCreatVoice.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/5.
//

#import "XMChatCreatVoice.h"
#import <AVFoundation/AVFoundation.h>
#import <ImSDK_Plus/ImSDK_Plus.h>

@interface XMChatCreatVoice () <AVAudioRecorderDelegate>

@property(nonatomic, strong) AVAudioRecorder *recorder;

@property(nonatomic, copy, readwrite) NSString *recordedFilePath;

@end

@implementation XMChatCreatVoice

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)record {
    [self creatSystemRecording];
}

- (void)stop {
    if ([self.recorder isRecording]) {
        [self.recorder stop];
        self.recorder = nil;
        if (self.delegate && [self.delegate respondsToSelector:@selector(creatVoiceSuccess:)]) {
            [self.delegate creatVoiceSuccess:self.recordedFilePath];
        }
    }
}

- (void)creatSystemRecording {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [session setActive:YES error:&error];
    if (error) {
        NSLog(@"发成错误%@", error);
    }

    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                            /**
                                                             * Sampling rate: 8000/11025/22050/44100/96000 (this parameter affects the audio
                                                             * quality)
                                                             */
                                                            [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                                                            /**
                                                             * Audio format
                                                             */
                                                            [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                                            /**
                                                             * Sampling bits: 8, 16, 24, 32, default is 16
                                                             */
                                                            [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                                                            /**
                                                             * Number of audio channels 1 or 2
                                                             */
                                                            [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                                                            /**
                                                             * Recording quality
                                                             */
                                                            [NSNumber numberWithInt:AVAudioQualityHigh], AVEncoderAudioQualityKey, nil];
    [self createRecordedFilePath];
    NSURL *url = [NSURL fileURLWithPath:self.recordedFilePath];
    NSError *fileError = nil;
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&fileError];
    if (fileError) {
        NSLog(@"文件生成失败%@", fileError);
    }
    self.recorder.delegate = self;
    self.recorder.meteringEnabled = YES;
    if ([self.recorder prepareToRecord]) {
        [self.recorder record];
    }
}

- (void)createRecordedFilePath {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Cache/AudioData"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = false;
    BOOL isDreExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if (!(isDir && isDreExist)) {
        NSError *error = nil;
        BOOL bCreaterDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        if (!bCreaterDir) {
            NSLog(@"创建失败");
        }
    }
    NSString *dateStr = [[NSDate date] dateStringWithFormat:@"yyyy_MM_dd_HH_mm_ss"];
    path = [path stringByAppendingFormat:@"/%@.MP3", dateStr];
    
    self.recordedFilePath = path;
    
//    self.recordedFilePath = [TUIKit_Voice_Path stringByAppendingString:[self genVoiceName:nil withExtension:@"MP3"]];
}

#pragma mark - Delegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    NSLog(@"成功");
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    NSLog(@"失败%@", error);
}

- (NSString *)genVoiceName:(NSString *)uuid withExtension:(NSString *)extent {
    NSString *identifier = [[V2TIMManager sharedInstance] getLoginUser];
    if (uuid == nil) {
        uuid = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    }
    NSString *name = [NSString stringWithFormat:@"%d_%@_voice_%@.%@", ImSDKAppId, identifier, uuid, extent];
    return name;
}

@end
